from django.shortcuts import render

# Create your views here.
from django.contrib.auth import login
from django.shortcuts import render
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.http import JsonResponse
import json, re
from oauth.models import OAuthQQUser
from oauth.utils import generate_access_token, check_access_token
from django_redis import get_redis_connection

from users.models import User


class QQFirstView(View):

    def get(self, request):
        '''返回qq登录的网址'''

        # 1.接收参数
        next = request.GET.get('next')

        # 2.导入工具类, 利用工具类创建对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
        # 3.调用对象的方法, 获取qq登录的网址
        login_url = oauth.get_qq_url()
        # 4.编辑json, 返回
        return JsonResponse({'code':0,
                             'errmsg':'ok',
                             'login_url':login_url})

import logging
logger = logging.getLogger('django')

class QQSecondView(View):

    def get(self, request):
        '''接收code参数, 判断openid是否在数据库,如果在,登录成功, 如果不在加密返回'''

        # 1.接收code参数
        code = request.GET.get('code')

        # 2.检验是否为空
        if not code:
            return JsonResponse({'code': 400,
                          'errmsg': '参数不存在',})
        # 3.创建工具类的对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
            # 4.调用对象的方法, 发送请求(code), 获取access_token
        access_token = oauth.get_access_token(code)

            # 5.调用对象的方法, 发送请求(access_token), 获取openid
        openid = oauth.get_open_id(access_token)
        # 6.判断openid是否在qq的表中
        try:
            oauth_qq = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            # 7.如果不在, 把openid加密为access_token, 返回
            # 11. 把openid加密access_token
            access_token = generate_access_token(openid)

            # 12. 把token返回
            return JsonResponse({'code':300,
                                 'errmsg':'ok',
                                 'access_token':access_token})

        else:
            user = oauth_qq.user

            # 8.如果在, 状态保持
            login(request, user)

            response = JsonResponse({'code':0,
                                     'errmsg':'ok'})

            # 9.往cookie中写入username
            response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

            # 10.返回json
            return response



    def post(self, request):
        '''保存绑定的信息'''
        pass
        # 1.接收json参数
        dict = json.loads(request.body)
        mobile = dict.get('mobile')
        password = dict.get('password')
        sms_code_client = dict.get('sms_code')
        access_token = dict.get('access_token')

        # 2.整体检验
        if not all([mobile, sms_code_client, password, access_token]):
            return JsonResponse({'code': 400,
                                 'errmsg': "缺少参数"})

        # 3.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': "mobile有误"})

        # 4.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'code': 400,
                                 'errmsg': "password有误"})

        # 5.链接redis, 获取redis的链接对象
        redis_conn = get_redis_connection('verify_code')

        # 6.从redis中获取服务端的短信验证码
        redis_conn = get_redis_connection('verify_code')

        # 6.从redis中获取服务端的短信验证码
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 7.判断服务端的短信验证码是否存在
        if not sms_code_server:
            return JsonResponse({'code': 400,
                                 'errmsg': "sms_code过期"})

        # 8.比对前后端的短信验证码
        if sms_code_client != sms_code_server.decode():
            return JsonResponse({'code': 400,
                                 'errmsg': "两个验证码不一致"})

        # 9.自定义一个函数用来解密access_token
        openid = check_access_token(access_token)
        # 10.判断该openid是否存在
        if openid is None:
            return JsonResponse({'code':400,
                                 'errmsg':"access_token有误"})

        # 11.从User表中取出该mobile对应的用户
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            # 12.如果取不到, 往User中增加一个mobile用户
            user = User.objects.create_user(username=mobile,
                                            password=password,
                                            mobile=mobile)
        else:
            # 13.如果取到了, 检验密码(passwrod), 如果密码不对, return
            if not user.check_password(password):
                return JsonResponse({'code': 400,
                                     'errmsg': "密码错误"})
        # 14.把openid保存到qq表中
        try:
            OAuthQQUser.objects.create(openid=openid,
                                       user=user)
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': "qq保存失败"})
        # 15.状态保持
        login(request,user)

        response = JsonResponse({'code':0,
                                 'errmsg':'ok'})
        # 16.往cookie中写入username
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        # 17.返回json
        return response